// 云函数入口文件
const cloud = require("wx-server-sdk");

cloud.init();

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();

  cloud.updateConfig({
    env: wxContext.ENV == "local" ? "test-go5gy" : wxContext.ENV
  });

  const db = cloud.database();

  const { pageIndex } = event;

  const _ = db.command

  const $ = _.aggregate;

  const userCount = await db.collection('bookshelfs')
    .aggregate()
    .group({
      _id: "$_openid",
    })
    .count('userCount')
    .end();
  let count = 0;
  if (userCount.errMsg == 'collection.aggregate:ok') {
    count = userCount.list[0].userCount
  }

  const res = await db
    .collection("bookshelfs")
    .aggregate()
    .group({
      _id: "$_openid",
      books: $.push({
        name: '$name',
        read_time: '$read_time',
        author: '$author',
        source_id: '$source_id',
        read_url: '$read_url'
      })
    })
    .lookup({
      from: 'users',
      localField: '_id',
      foreignField: '_id',
      as: 'user'
    })
    .replaceRoot({
      newRoot: $.mergeObjects([$.arrayElemAt(['$user', 0]), '$$ROOT'])
    })
    .project({
      user: 0
    })
    .sort({
      _id: 1
    })
    .skip(pageIndex * 10)
    .limit(10)
    .end();

  if (res.errMsg == 'collection.aggregate:ok') {
    return { errMsg: 'ok', data: { list: res.list, total: count } }
  }

  return { errMsg: res.errMsg, data: [] }
};
